package login

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	loginutils "hft/Http/Services/login/login_utils"
	"hft/e"
	"hft/global"
	"hft/tools"
)

type Login struct{}

// 站长登陆
func (l *Login) SiteLogin(column string, value interface{}, userType string) (data interface{}, err error) {

	return nil, nil
}

// 普通登录
func (l *Login) NormalLogin(column string, value interface{}, userType string) (token string, err error) {

	var nowAccount *admin.Account
	var role *admin.Role
	err = global.OC_DB.Where(fmt.Sprintf("%v = ?", column), value).First(&nowAccount).Error
	if err != nil {
		return "", errors.New(e.AccountNotExist)
	}
	err = global.OC_DB.First(&role, nowAccount.RoleId).Error
	if err != nil {
		return "", errors.New(e.RoleNotExist)
	}
	if role.LoginPage != userType {
		return "", errors.New(e.AccountNotExist)
	}
	if !nowAccount.Status {
		return "", errors.New(e.AccountHasBeenBan)
	}
	var claims = &tools.BaseClaims{
		Username: nowAccount.Username,
		RealName: nowAccount.RealName,
		Belong:   int(nowAccount.Belong),
		Status:   nowAccount.Status,
		Link:     nowAccount.RegionLink,
		UserID:   nowAccount.ID,
		UserType: userType,
		RoleID:   nowAccount.RoleId,
	}
	// 设置当前的登陆站点
	if nowAccount.RoleId == 32 {
		fmt.Println("asdasdasd", nowAccount.Username, nowAccount.Belong)
		global.OC_REDIS.Set(fmt.Sprintf("SITE_LOGIN-%v", nowAccount.Username), nowAccount.Belong, -1)
	}
	token, err = loginutils.GenerateToken(*claims, userType)
	if err != nil {
		return "", err
	}

	return token, nil
}

func (l *Login) SendCode(prefix string, phone string) (err error) {

	var model string
	var res = tools.CheckPhoneNumber(phone)
	if res == 0 {
		model = global.OC_CONFIG.AliyunSms.SmsModel
	} else if res == 1 {
		phone = "852" + phone
		model = global.OC_CONFIG.AliyunSms.SmsHKModel
	} else if res == 2 {
		phone = "853" + phone
		model = global.OC_CONFIG.AliyunSms.SmsHKModel
	} else {
		return errors.New(e.PhoneNotRight)
	}

	tools.AliyunSmsTool.SendValid(prefix, phone, model)

	return nil
}

func (l *Login) ValidCode(prefix string, phone string, code string) (err error) {

	err = tools.AliyunSmsTool.VerifyValid(prefix, phone, code)

	return

}

var LoginService = new(Login)
